﻿/*!
 * zkx.js v1.0
 * (c) 2018 xlingopen@126.com
 * Released under the MIT License.
 */
/* 异步请求结果返回状态码 */
//var ResultStatus = { OK: 100, Failed: 101, NotLogin: 102, Unauthorized: 103 };
layui.define(['layer'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;

    var core = {

        debounce: function (func, wait, immediate) {
            // immediate默认为false
            var timeout, args, context, timestamp, result;

            var later = function () {
                // 当wait指定的时间间隔期间多次调用_.debounce返回的函数，则会不断更新timestamp的值，导致last < wait && last >= 0一直为true，从而不断启动新的计时器延时执行func
                var last = _.now() - timestamp;

                if (last < wait && last >= 0) {
                    timeout = setTimeout(later, wait - last);
                } else {
                    timeout = null;
                    if (!immediate) {
                        result = func.apply(context, args);
                        if (!timeout) context = args = null;
                    }
                }
            };

            return function () {
                context = this;
                args = arguments;
                timestamp = _.now();
                // 第一次调用该方法时，且immediate为true，则调用func函数
                var callNow = immediate && !timeout;
                // 在wait指定的时间间隔内首次调用该方法，则启动计时器定时调用func函数
                if (!timeout) timeout = setTimeout(later, wait);
                if (callNow) {
                    result = func.apply(context, args);
                    context = args = null;
                }

                return result;
            };
        },
        guid: function () {

            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        }
        , get: function (url, data, callback) {
            if ($.isFunction(data)) {
                callback = data;
                data = undefined;
            }

            url = parseUrl(url);
            var ret = execAjax("GET", url, data, callback);
            return ret;
        }
        , post: function (url, data, callback) {
            if ($.isFunction(data)) {
                callback = data;
                data = undefined;
            }

            var ret = execAjax("POST", url, data, callback);
            return ret;
        }
        , extra_data: function (input, data) {
            debugger;
            var item = [];
            $.each(data, function (k, v) {
                item.push('<input type="hidden" name="' + k + '" value="' + v + '">');
            })
            $(input).after(item.join(''));
        }
        , alert: function (msg, callBack, icon) {
            coreAlert(msg, callBack, icon);
        }
        , confirm: function (msg, callBack) {
            layerConfirm(msg, callBack);
        }
        , msg: function (msg, callBack, icon, time) {
            coreMsg(msg, callBack, icon, time);
        }
        , reload: function () {
            location.reload();
            return false;
        }
        , highlight: function ($el, keyword) {
            if (keyword) {
                var ym = $el.html();//.innerHTML;//ss是要高亮的区域，div的id值
                $el.html(ym.replace(keyword, "<span class='highlight_word'>" + keyword + "</span>"));
                //document.getElementById(id).innerHTML = ym.replace(keyword, "<span class='highlight_word'>" + keyword + "</span>");
            }
        }
        , getQueryParam: function (name) {
            if (name === null || name === undefined || name === "")
                return "";
            name = ("" + name).toLowerCase();
            var search = location.search.slice(1);
            var arr = search.split("&");
            for (var i = 0; i < arr.length; i++) {
                var ar = arr[i].split("=");
                if (ar[0].toLowerCase() === name) {
                    if (unescape(ar[1]) === 'undefined') {
                        return "";
                    } else {
                        return unescape(ar[1]);
                    }
                }
            }
            return "";
        }
        , getQueryParams: function () {
            var params = {};
            var loc = window.location;
            var se = decodeURIComponent(loc.search);

            if (!se) {
                return params;
            }

            var paramsString;
            paramsString = se.substr(1);//将?去掉
            var arr = paramsString.split("&");
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                var index = item.indexOf("=");
                if (index === -1)
                    continue;
                var paramName = item.substr(0, index);
                if (!paramName)
                    continue;
                var value = item.substr(index + 1);
                params[paramName] = value;
            }
            return params;
        }
        , getOptionTextByValue: function (optionList, value, valuePropName, textPropName) {
            valuePropName = valuePropName || "Value";
            textPropName = textPropName || "Text";

            var text = "";
            var len = optionList.length;
            for (var i = 0; i < len; i++) {
                if (optionList[i][valuePropName] === value) {
                    text = optionList[i][textPropName];
                    break;
                }
            }

            return text;
        }
        , selectRow: function (selectedTr) {

            var c = "warning";
            $(selectedTr).addClass(c);
            $(selectedTr).siblings().removeClass(c);
            return true;
        }
        , formatBool: function (val) {
            if (val === true) {
                return "是";
            }
            else if (val === false) {
                return "否";
            }

            return val;
        }
        , download: function (url, method) {
            if (url) {

                $('<form action="' + url + '" method="' + (method || 'post') + '"></form>').appendTo('body').submit().remove();
            };
        }
        , upload: function (url, data) {
            if (url && data) {
                data = typeof data === 'string' ? data : jQuery.param(data);
                var inputs = '';
                $.each(data.split('&'), function () {
                    var pair = this.split('=');
                    inputs += '<input type="file" name="' + pair[0] + '" value="' + pair[1] + '" />';
                });
                $('<form enctype="multipart/form-data"    action="' + url + '" method="' + ('post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
            };
        }
        , LoadVueComponents: function (components) {
            var deferred = $.Deferred();
            //加载Vue组件
            require(["/Content/vueTemplates/_loader.js"], function (loader) {
                loader.Load(components).then(function () {
                    deferred.resolve();
                });
            });
            return deferred;
        }
        , clone: function (obj) {
            return JSON.parse(JSON.stringify(obj));
        }
    };
    core.LoadVueComponents(["ling-footer", "checkbutton", "switchbutton"]); // , "ling-ulfooter"

    //静态扩展
    (function () {
        Date.prototype.format = function (format) {
            var o =
            {
                "M+": this.getMonth() + 1, //month
                "d+": this.getDate(),    //day
                "H+": this.getHours(),   //hour
                "m+": this.getMinutes(), //minute
                "s+": this.getSeconds(), //second
                "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
                "S": this.getMilliseconds() //millisecond
            };
            if (/(y+)/.test(format))
                format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(format))
                    format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            return format;
        };
        Array.prototype.where = function (predicate) {
            var arr = this;
            var retArr = [];
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                if (predicate(item)) {
                    retArr.push(item);
                }
            }
            return retArr;
        };
        Array.prototype.select = function (selector) {
            var arr = this;
            var retArr = [];
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                retArr.push(selector(item));
            }
            return retArr;
        };
        Array.prototype.first = function (predicate) {
            var arr = this;
            var retArr = [];
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                if (predicate(item)) {
                    return item;
                }
            }
            return retArr;
        };
        Array.prototype.getIndex = function (id) {
            var arr = this;
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i].Id;
                if (id === item) {
                    return i;
                }
            }
            return -1;
        };
    })();

    //jQuery扩展
    (function () {
        $.fn.extend({
            Grid: function (options, mixins) {
                var el = $(this)[0];
                var vue;
                var vm = {
                    el: el,
                    data: {
                        //tool
                        SearchModel: {
                            keyword: ""
                        },//搜索
                        SearchMapModel: { keyword: "" },
                        SearchOneUrl: null,//单个model的查询
                        SearchUrl: null,//查询url
                        SearchListUrl: null,//不分页的查询
                        SearchMapUrl: null,//查询url
                        AddMapUrl: null,
                        EditMapUrl: null,
                        DeleteMapUrl: null,//删除 
                        AddUrl: null,
                        EditUrl: null,
                        DeleteUrl: null,//删除
                        EnableUrl: null,//启用或禁用
                        PrintUrl: null,//打印
                        ExportUrl: null,//导出
                        ImportUrl: null,//导入
                        DetailUrl: null,//通过Id获取明细的url
                        MultiActionUrl: null,
                        MultiActionName: null,
                        ModelKeyName: "Id", /* 实体主键名称 */
                        SelectAll: false,//全选
                        SelectedIDs: [],//当前页勾选的id列表 
                        //IsDetail: false,//是否显示详细页面
                        //tabel
                        Models: [],
                        Maps: [],
                        SelectedModel: null,
                        SelectedMap: null,
                        OptionsUrl: [],//多个下拉框的url
                        OptionItems: [],
                        PageOptions: {
                            ShowFirstPage: false,
                            ShowLastPage: false,
                            TotalCount: 0,
                            TotalPage: 0,
                            CurrentPage: 0,
                            SkipPage: 0,
                            PageSize: 20,
                            ShowPages: null,
                            AllowChangePageSize: true
                        },

                        PageMapOptions: {
                            ShowFirstPage: false,
                            ShowLastPage: false,
                            TotalCount: 0,
                            TotalPage: 0,
                            CurrentPage: 0,
                            SkipPage: 0,
                            PageSize: 10,
                            ShowPages: null,
                            AllowChangePageSize: false
                        },
                        //dailog
                        Title: "提示",
                        EditModel: null,
                        EditMapModel: null,
                        Model: {},//绑定到界面的 model  
                        Map: {},
                        RowIndex: 0
                    },
                    methods: {
                        OnSetPagedMapData: function (pagedData) {
                            this.RowIndex = 0;
                            this.Maps = pagedData.DataList || pagedData;

                            if (pagedData.DataList) {
                                this.PageMapOptions.TotalCount = pagedData.TotalCount;
                                this.PageMapOptions.TotalPage = pagedData.TotalPage;
                                this.PageMapOptions.CurrentPage = pagedData.CurrentPage;
                                this.PageMapOptions.SkipPage = pagedData.CurrentPage;
                                this.PageMapOptions.PageSize = pagedData.PageSize;

                                var showPageCount = 6;

                                var min = this.PageMapOptions.CurrentPage - (showPageCount / 2);

                                if (min < 1)
                                    min = 1;

                                var max = min + showPageCount;

                                if (max > this.PageMapOptions.TotalPage) {
                                    max = this.PageMapOptions.TotalPage;
                                    min = max - showPageCount;
                                    if (min < 1)
                                        min = 1;
                                }

                                var showPages = [];
                                for (var i = min; i <= max; i++) {
                                    showPages.push(i);
                                }
                                this.PageMapOptions.ShowPages = showPages;

                                this.PageMapOptions.ShowFirstPage = (min !== 1);
                                this.PageMapOptions.ShowLastPage = (max !== this.PageMapOptions.TotalPage);
                            }
                        },
                        OnSetPagedData: function (pagedData) {
                            this.RowIndex = 0;
                            this.Models = pagedData.DataList || pagedData;

                            if (pagedData.DataList) {
                                this.PageOptions.TotalCount = pagedData.TotalCount;
                                this.PageOptions.TotalPage = pagedData.TotalPage;
                                this.PageOptions.CurrentPage = pagedData.CurrentPage;
                                this.PageOptions.SkipPage = pagedData.CurrentPage;
                                this.PageOptions.PageSize = pagedData.PageSize;

                                var showPageCount = 6;

                                var min = this.PageOptions.CurrentPage - (showPageCount / 2);

                                if (min < 1)
                                    min = 1;

                                var max = min + showPageCount;

                                if (max > this.PageOptions.TotalPage) {
                                    max = this.PageOptions.TotalPage;
                                    min = max - showPageCount;
                                    if (min < 1)
                                        min = 1;
                                }

                                var showPages = [];
                                for (var i = min; i <= max; i++) {
                                    showPages.push(i);
                                }
                                this.PageOptions.ShowPages = showPages;

                                this.PageOptions.ShowFirstPage = (min !== 1);
                                this.PageOptions.ShowLastPage = (max !== this.PageOptions.TotalPage);
                            }
                        },

                        Init: function () {
                            if (vue.OnInit) {
                                vue.OnInit();
                            }
                            this.OnSearch();
                            this.OnGetOptions();//加载下拉列表
                            if (vue.OnLoad)
                                vue.OnLoad();
                        },
                        Search: function () {
                            this.OnSearch();
                        },
                        SearchList: function () {
                            this.OnSearchList();
                        },
                        SearchMap: function () {
                            this.OnSearchMap();
                        },
                        OnGetOptions: function (page) {
                            var that = this;
                            if (this.OptionsUrl === null) //[url1,rul2]
                                throw new Error("未指定 OptionsUrl");
                            if (!that.OptionItems) that.OptionItems = [];
                            var list = this.OptionsUrl;
                            $.each(list, function (index, url) {
                                core.get(url, null, function (result) {
                                    that.OptionItems.splice(index, 0, result.data);
                                });
                            });
                        },
                        OnSearch: function (page) {
                            var that = this;
                            if (this.SearchUrl === null && this.SearchOneUrl === null)
                                throw new Error("未指定 SearchUrl 或 SearchOneUrl");
                            if (this.SearchOneUrl !== null) { //单个model的搜索
                                var url = this.SearchOneUrl;
                                var data = this.SearchModel;
                                core.get(url, data, function (result) {
                                    that.Model = result.data;
                                    that.EditModel = result.data;
                                    if (vue.OnSearched)
                                        vue.OnSearched();
                                });
                            }
                            else {
                                var url = this.SearchUrl;

                                this.SelectedModel = null;
                                var data = this.SearchModel;
                                data.page = page || 1;
                                data.pageSize = this.PageOptions.PageSize;
                                core.get(url, data, function (result) {
                                    that.OnSetPagedData(result.data);
                                    if (vue.OnSearched)
                                        vue.OnSearched();
                                });
                            }
                        },

                        OnSearchList: function () {
                            var that = this;
                            if (this.SearchListUrl === null && this.SearchOneUrl === null)
                                throw new Error("未指定 SearchListUrl 或 SearchOneUrl");
                            if (this.SearchOneUrl !== null) { //单个model的搜索
                                var url = this.SearchOneUrl;
                                var data = this.SearchModel;
                                core.get(url, data, function (result) {
                                    that.Model = result.data;
                                    that.EditModel = result.data;
                                    if (vue.OnSearched)
                                        vue.OnSearched();
                                });
                            }
                            else {
                                var url = this.SearchListUrl;

                                this.SelectedModel = null;
                                var data = this.SearchModel;
                                core.get(url, data, function (result) {
                                    that.RowIndex = 0;
                                    that.Models = (result.data);
                                    if (vue.OnSearched)
                                        vue.OnSearched();
                                });
                            }
                        },


                        OnSearchMap: function (page) {
                            var that = this;
                            if (this.SearchMapUrl === null)
                                throw new Error("未指定 SearchMapUrl");
                            var url = this.SearchMapUrl;
                            this.SelectedMap = null;
                            var data = this.SearchMapModel;
                            data.page = page || 1;
                            if (!data.pageSize)
                                data.pageSize = this.PageMapOptions.PageSize;
                            core.get(url, data, function (result) {
                                that.OnSetPagedMapData(result.data);
                                that.Map = null;
                                that.EditMapModel = null;
                            });
                        },
                        //GetDetail: function (id) {
                        //    if (this.DetailUrl === null)
                        //        throw new Error("未指定 DetailUrl");
                        //    var that = this;
                        //    core.get(this.DetailUrl, { id: id }, function (result) {

                        //        if (result.code === 0) {
                        //            that.SelectedModel = result.data;
                        //        }
                        //        else {
                        //            core.msg(result.msg);
                        //            return;
                        //        }
                        //    });
                        //},
                        //Detail: function (id, name) {
                        //    if (id)
                        //        this.GetDetail(id);
                        //    this.IsDetail = true;
                        //},
                        Add: function (name) {
                            this.Open(name, "添加");
                        },
                        ChangeStatus: function (keyId) {
                            var that = this;
                            if (keyId && this.EnableUrl) {

                                var params = { id: keyId };
                                core.post(this.EnableUrl, params, function (result) {
                                    var msg = result.msg || "审核成功";
                                    core.msg(msg);
                                    that.OnSearch();
                                });
                            }
                            if (this.Model) {
                                this.Model.IsEnabled = !this.Model.IsEnabled;


                            }
                        },
                        Delete: function (keyId) {
                            var that = this;
                            if (this.DeleteUrl === null)
                                throw new Error("未指定 DeleteUrl");
                            var url = this.DeleteUrl;

                            var deleteId;

                            if (this.SelectedModel)
                                deleteId = this.SelectedModel[this.ModelKeyName];
                            else deleteId = keyId;
                            var params = { id: deleteId };

                            core.confirm("确定要删除该条数据吗？", function () {

                                core.post(url, params, function (result) {
                                    var msg = result.msg || "删除成功";
                                    core.msg(msg);
                                    that.RemoveSelectedModel();
                                    that.OnSearch();
                                });
                            });
                        },
                        DeleteMap: function (keyId) {
                            var that = this;
                            if (this.DeleteMapUrl === null)
                                throw new Error("未指定 DeleteMapUrl");
                            var url = this.DeleteMapUrl;

                            var deleteId;

                            if (this.SelectedMap)
                                deleteId = this.SelectedMap[this.ModelKeyName];
                            else deleteId = keyId;
                            var params = { id: deleteId };

                            core.confirm("确定要删除该条数据吗？", function () {

                                core.post(url, params, function (result) {
                                    var msg = result.msg || "删除成功";
                                    core.msg(msg);
                                    that.RemoveSelectedMap();
                                    that.OnSearchMap();
                                });
                            });
                        },
                        Edit: function (name, model) {
                            if (model)
                                this.SelectedModel = model;
                            this.Open(name, "修改", this.SelectedModel);
                        },
                        EditMap: function (model) {
                            if (model) {
                                this.SelectedMap = model;
                                this.EditMapModel = model;
                            }
                            else {
                                this.EditMapModel = null;
                            }
                        },
                        IsEditMap: function (id) {
                            if (this.EditMapModel && this.EditMapModel.Id === id) {
                                return true;
                            }
                            else
                                return false;
                        },
                        CancelEditMap: function (model) {
                            this.EditMapModel = null;
                        },
                        Import: function (name) {
                            this.Open(name, "导入");
                        },
                        DownLoad: function () {
                            if (this.ExportUrl === null)
                                throw new Error("未指定 ExportUrl");
                            var url = this.ExportUrl;
                            core.download(url, 'get');
                        },
                        Disabled: function () {
                            return this.SelectedModel === null;
                        },
                        DisabledMap: function () {
                            return this.SelectedMap === null;
                        },


                        /* table */
                        SelectRow: function (model) {
                            this.SelectedModel = model;
                        },
                        SelectLeftRow: function (model) {
                            this.Model = {};
                            if (model) {
                                this.EditModel = model;
                            }
                            else {
                                this.EditModel = null;
                            }
                            if (this.EditModel) {
                                this.Model = this.EditModel;
                            }
                            else {
                                this.Model = {
                                    IsEnabled: true
                                };
                            }
                        },
                        SelectMap: function (model) {
                            this.SelectedMap = model;
                        },
                        RemoveSelectedModel: function () {
                            if (this.SelectedModel) {
                                var index = this.Models.getIndex(this.SelectedModel.Id);
                                this.Models.splice(index, 1); //这个方法太坑了，不能使用remove
                            }
                        },
                        RemoveSelectedMap: function () {
                            if (this.SelectedMap) {
                                var index = this.Maps.getIndex(this.SelectedMap.Id);
                                this.Models.splice(index, 1); //这个方法太坑了，不能使用remove
                            }
                        },
                        SetModels: function (models) {
                            this.RowIndex = 0;
                            this.Models = models;
                        },
                        ToFixed: function (value, decimal) {
                            return value.toFixed(decimal);
                        },
                        OnClickItem: function (name, model) {
                            this.SelectedModel = model;
                            if (vue.ClickItem)
                                vue.ClickItem(name, model);
                        },
                        GetOrdinalIndex: function () {
                            return RowIndex++;
                        },
                        GetOrdinal: function ($index) {
                            return (this.PageOptions.CurrentPage - 1) * this.PageOptions.PageSize + $index + 1;
                        },
                        GetOrdinalMap: function ($index) {
                            return (this.PageMapOptions.CurrentPage - 1) * this.PageMapOptions.PageSize + $index + 1;
                        },
                        GetOptionTextByValue: function (index, value, valuePropName, textPropName) {
                            if (this.OptionItems === null || this.OptionItems.length <= 0) return "";
                            valuePropName = valuePropName || "Value";
                            textPropName = textPropName || "Text";
                            var text = "";
                            var len = this.OptionItems[index].length;
                            for (var i = 0; i < len; i++) {
                                if (this.OptionItems[index][i][valuePropName] === value) {
                                    text = this.OptionItems[index][i][textPropName];
                                    break;
                                }
                            }

                            return text;
                        },
                        ToMapPage: function (page) {
                            if (page < 1 || page > this.PageMapOptions.TotalPage)//|| page === this.CurrentPage
                                return;
                            this.OnSearchMap(page);
                        },
                        ToPage: function (page) {
                            if (page < 1 || page > this.PageOptions.TotalPage)//|| page === this.CurrentPage
                                return;
                            this.OnSearch(page);
                        },
                        appendRetract: function (level) {
                            var s = "";
                            for (var i = 0; i < level * 4; i++) {
                                s += "&nbsp;";
                            }
                            return s;
                        },
                        expandChildren: function (parentEle, clickEle, hideParent) {
                            $arrow = $(clickEle || parentEle);
                            var $tbody = $arrow.parents('tbody');
                            var $parentTr = $(parentEle).parents('tr').eq(0);
                            var key = "hide_" + $parentTr.attr("id");
                            if (!clickEle) {
                                window[key] = !window[key];
                                $(parentEle).toggleClass("fa-caret-down").toggleClass("fa-caret-right");
                            }
                            var parentId = $parentTr.attr("id");
                            var $children = $tbody.find("tr[parent-id='" + parentId + "']");
                            var hideChildren = hideParent || window[key];
                            var that = this;
                            $.each($children, function (index, child) {
                                hideChildren ? $(child).hide() : $(child).show();
                                that.expandChildren($(child).find(".glyphicon").eq(0), $arrow, hideChildren);
                            });
                        },
                        Open: function (name, title, model) {
                            var that = this;

                            this.Model = {};
                            if (model) {
                                this.EditModel = model;
                            }
                            else {
                                this.EditModel = null;
                            }

                            if (title)
                                this.Title = title;
                            if (this.EditModel) {
                                this.Model = this.EditModel;
                            }
                            else {
                                this.Model = {
                                    IsEnabled: true
                                };
                            }
                            if (vue.Openning) {
                                vue.Openning(name);
                            }
                            if (vue.DialogConfig) {
                                var config = vue.DialogConfig(name);
                                config.content.OldParent = $(config.content).parent();
                                vue.DialogContent = config.content;
                                var dialogIndex;
                                layer.open({
                                    type: config.type || 1,
                                    maxmin: config.maxmin || false,
                                    anim: 1,
                                    resize: false,
                                    title: config.title,
                                    area: config.area, //宽高
                                    content: config.content,
                                    success: function (layero, index) {
                                        //遮盖层位置调整
                                        $(layero).appendTo("body");
                                        if (config.opened)
                                            config.opened(index);
                                    },
                                    end: function () {
                                        if (vue.DialogContent) {
                                            $(vue.DialogContent).appendTo(vue.DialogContent.OldParent);
                                        }
                                        if (config.end)
                                            config.end();

                                    }
                                });
                                setTimeout(function () {
                                    if (config.after)
                                        config.after();
                                    //执行完毕，layer的动画一般是执行300毫秒
                                }, 500);

                            }
                        },

                        Save: function () {
                            var retCode = 0;//默认正确
                            var that = this;
                            var model = this.Model;
                            if (this.EditModel) {
                                if (this.EditUrl === null)
                                    throw new Error("未指定 EditUrl");
                                var data = this.EditModel;
                                if (this.EditModel.Data) {
                                    data = this.EditModel.Data;
                                }
                                core.post(this.EditUrl, data, function (result) {
                                    if (result.code === 0) {
                                        retCode = 0;
                                        that.OnSearch();
                                        core.msg(result.msg || '更新成功', null, 6, 1000);
                                    }
                                    else {
                                        core.alert(result.msg);
                                    }
                                }
                                );
                            }
                            else {
                                if (this.AddUrl === null)
                                    throw new Error("未指定 AddUrl");
                                core.post(this.AddUrl, model, function (result) {

                                    if (result.code === 0) {
                                        retCode = 0;
                                        that.OnSearch();
                                        core.msg(result.msg || '更新成功', null, 6, 1000);

                                    }
                                    else {
                                        core.alert(result.msg);
                                    }
                                }
                                );
                            }

                            if (vue.OnSaved)
                                vue.OnSaved(el);

                            return retCode;
                        },
                        SaveMap: function () {
                            var retCode = 0;//默认正确
                            var that = this;
                            var model = this.Map;
                            if (this.EditMapModel) {
                                if (this.EditMapUrl === null)
                                    throw new Error("未指定 EditMapUrl");
                                core.post(this.EditMapUrl, this.EditMapModel, function (result) {
                                    if (result.code === 0) {
                                        retCode = 0;
                                        that.OnSearchMap();
                                        core.msg(result.msg || '更新成功', null, 6, 1000);
                                    }
                                    else {
                                        core.alert(result.msg);
                                    }
                                }
                                );
                            }
                            else {
                                if (this.AddMapUrl === null)
                                    throw new Error("未指定 AddMapUrl");
                                core.post(this.AddMapUrl, model, function (result) {

                                    if (result.code === 0) {
                                        retCode = 0;
                                        that.OnSearchMap();
                                        core.msg(result.msg || '更新成功', null, 6, 1000);
                                    }
                                    else {
                                        core.alert(result.msg);
                                    }
                                }
                                );
                            }
                            return retCode;
                        },
                        Any: function (value) {
                            if (value === undefined || value === null) { return false; }
                            else {
                                if (value.length <= 0) return false;
                                return true;
                            }
                        },
                        FromJson: function (str) {
                            if (str) {
                                var _str = JSON.parse(str);
                                console.log(_str);
                                return _str;
                            }
                            else return [];
                        },
                        ToJson: function (obj) {
                            if (obj) {
                                var _obj = JSON.stringify(obj);
                                console.log(_obj);
                                return _obj;
                            }
                            else return "";
                        }
                    },
                    filters: {
                        yyyy_mm_dd: function (value) {
                            if (value && value.length > 10)
                                return value.substr(0, 10);
                            else return value;
                        },
                        yyyy_mm_dd_hh_mm_ss: function (value) {

                            if (value === undefined) {
                                return "";
                            }
                            return value.replace('T', ' ');
                        },
                        Gender: function (value) {
                            if (value === undefined) {
                                return "男";
                            }
                            return value === 1 ? '男' : '女';
                        },
                        YesOrNo: function (value) {
                            if (value === undefined) {
                                return "否";
                            }
                            return value ? '是' : '否';
                        },
                        Status: function (value) {
                            if (value === undefined) {
                                return "禁用";
                            }
                            return value ? '启用' : '禁用';
                        },
                        Count: function (value) {
                            if (value === undefined) { return 0; }
                            else {
                                return value.length;
                            }
                        },

                        FileSize: function (value) {
                            if (value === undefined) { return 0 + " KB"; }
                            var fileSizeByte = value;
                            var fileSizeMsg = "";
                            if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(1) + " KB";
                            else if (fileSizeByte === 1048576) fileSizeMsg = " 1MB";
                            else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(1) + " MB";
                            else if (fileSizeByte > 1048576 && fileSizeByte === 1073741824) fileSizeMsg = " 1GB";
                            else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(1) + " GB";
                            else fileSizeMsg = "文件超过1TB";
                            return fileSizeMsg;
                        },
                        Target: function (val) {
                            if (val === "expand") {
                                return "无页面";
                            } else if (val === "iframe") {
                                return "框架页";
                            } else if (val === "default") {
                                return "内容页";
                            } else if (val === "blank") {
                                return "新窗口";
                            }
                            else if (val === "open") {
                                return "内容页";
                            }
                            return val;
                        }
                    },
                    mounted: function () { //加载完成 
                        if (options.mounted) {
                            options.mounted.call(this);
                        }


                        //console.log("vm mounted");
                    },
                    updated: function () {
                        //console.log("vm updated");
                        if (options.updated) {
                            options.updated.call(this);
                        }
                        if (vue.updated) {
                            vue.updated.call(vm);
                        }
                    },
                    beforeUpdate: function () {
                        if (options.beforeUpdate) {
                            options.beforeUpdate.call(this);
                        }
                        //console.log("vm beforeUpdate");
                    }
                };


                if (mixins) {
                    vm.mixins = [mixins];
                }
                if (options && options.data)
                    vm = $.extend(true, vm, { data: options.data });

                if (options && options.methods)
                    vm = $.extend(true, vm, { methods: options.methods });

                vue = new Vue(vm);

                if (options)
                    vue = $.extend(true, vue, options);


                vue.Init();
                return vue;
            }
            , Select: function (url, options) {
                var el = $(this)[0];
                var vue;
                var vm = new Vue({
                    el,
                    data: {
                        Items: [{ "Value": "8ad057a8643e4d769513a99a7a2c2113", "Text": "123" }, { "Value": "e3cbd06ae004424e9aae3d1beeee0fcd", "Text": "123" }, { "Value": "25fcfaed1ceb408b97905c8fe3a8b415", "Text": "123" }, { "Value": "64ac3e117acb48698e6ef410bba37342", "Text": "123" }, { "Value": "e7f62982f6e64277a9cc2956f12dfd6d", "Text": "123" }, { "Value": "48573e3b19314d659b2141dff58ebbce", "Text": "123" }]
                    },
                    mounted: function () { //加载完成 
                        // var that = this;
                        //    $.ajax({
                        //type: "get",
                        //url: url,
                        //        data: {
                        //            page: 1,
                        //            pageSize: 1000
                        //        },
                        //        dataType: "json"
                        //    }).then(function (result) { 
                        //        if (result && result.Data && result.Data) {
                        //            //that.Items = result.Data;
                        //            //setTimeout(function () {
                        //            //    form.render('select');
                        //            //}, 1);
                        //        }
                        //    });
                    }

                });
                if (options)
                    $.extend(vm, options);
                return vue;
            }
        });
    })();




    function execAjax(type, url, data, callback) {
        var layerIndex = layer.load(1, {
            shade: [0.3, '#000'] //0.3透明度的黑色背景
        });
        var ret = $.ajax({
            url: url,
            type: type,
            dataType: "json",
            data: data,
            complete: function (xhr) {
                layer.close(layerIndex);
            },
            success: function (result) {
                var isStandardResult = ("code" in result) && ("msg" in result);
                if (isStandardResult) {
                    if (result.code === -1) {
                        coreAlert(result.msg || "操作失败", null, 2);
                        return;
                    }
                    //if (result.Status === ResultStatus.NotLogin) {
                    //    layerAlert(result.Msg || "未登录或登录过期，请重新登录");
                    //    return;
                    //}
                    //if (result.Status === ResultStatus.Unauthorized) {
                    //    layerAlert(result.Msg || "权限不足，禁止访问");
                    //    return;
                    //}

                    if (result.code === 0) {
                        /* 传 result，用 result.Data 还是 result.Msg，由调用者决定 */
                        callback(result);
                    }
                }
                else
                    callback(result);
            },
            error: errorCallback
        });
        return ret;
    }
    function errorCallback(xhr, textStatus, errorThrown) {
        var json = { textStatus: textStatus, errorThrown: errorThrown };
        alert("请求失败: " + JSON.stringify(json));
    }
    function parseUrl(url) {
        if (url.indexOf("_dc=") < 0) {
            if (url.indexOf("?") >= 0) {
                url = url + "&_dc=" + (new Date().getTime());
            } else {
                url = url + "?_dc=" + (new Date().getTime());
            }
        }
        return url;
    }

    function coreAlert(msg, callBack, icon) {
        var idx;
        idx = layer.alert(msg, {
            icon: icon,
            title: "系统提示",
            btn: ['确认'],
        }, function () {
            layer.close(idx);
            if (callBack)
                callBack();
        });
    }
    function coreMsg(msg, callBack, icon, time) {
        msg = msg === null ? "" : msg;/* layer.msg 传 null 会报错 */
        layer.msg(msg, { icon: icon, time: time, shift: 0 }, function () {
            if (callBack)
                callBack();
        });
    }
    function layerAlert(msg, callBack) {
        msg = msg === null ? "" : msg;/* layer.alert 传 null 会报错 */
        var type = 'warning';
        var icon = "";
        if (type === 'success') {
            icon = 1;// "fa-check-circle";
        }
        if (type === 'error') {
            icon = "fa-times-circle";
        }
        if (type === 'warning') {
            icon = "fa-exclamation-circle";
        }

        var idx;
        idx = layer.alert(msg, {
            icon: icon,
            title: "系统提示",
            btn: ['确认'],
            btnclass: ['btn btn-primary'],
        }, function () {
            layer.close(idx);
            if (callBack)
                callBack();
        });
    }
    function layerConfirm(content, callBack, icon) {
        var idx;
        idx = layer.confirm(content, {
            icon: icon || 3,
            title: "系统提示",
            btn: ['确认', '取消'],
            //btnclass: ['btn btn-primary', 'btn btn-danger'],
        }, function () {
            layer.close(idx);
            callBack();
        }, function () {

        });
    }
    function layerMsg(msg, callBack) {
        msg = msg === null ? "" : msg;/* layer.msg 传 null 会报错 */
        layer.msg(msg, { time: 2000, shift: 0 });
    }

    //对外接口
    exports('ling', core);
});